package zengjin.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zengjin.common.R;
import zengjin.service.FileService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 19324
 * 文件上传和下载控制器
 */
@Tag(name = "文件相关接口")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${uploadLocation.path-file}")
    private String uploadPath;

    @Resource
    private FileService fileService;

    //1. 文件上传
    @Operation(summary = "文件上传")
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        log.info("文件上传开始");
        log.info("文件：" + file.toString());
        //file是一个临时文件，需要转存的指定位置，否则本次请求完成后临时文件会删除

        //获得原始文件名
        String originalFilename = file.getOriginalFilename();

        //TODO:使用uuid重新生成文件名，防止文件名重复，造成文件覆盖
        String suffix = null;
        if (originalFilename != null) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID() + suffix;

        //创建文件对象
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            //目录不存在，创建目录
            dir.mkdirs();
        }

        //将临时文件转存到指定位置
        file.transferTo(new File(uploadPath + fileName));

        return R.success(fileName, "上传成功");
    }


    //2. 文件下载
    @Operation(summary = "文件下载")
    @GetMapping("/download")
    public  void download(String name, HttpServletResponse response) throws Exception {
        // 设置响应头，指定下载文件的名称和后缀
        response.setHeader("Content-Disposition", "attachment; filename=" + name);
        //1.输入流，读取文件内容
        FileInputStream fileInputStream = new FileInputStream(uploadPath + name);
        log.info("文件下载开始");
        System.out.println(name);

        //2.输出流，将文件写回浏览器

        ServletOutputStream outputStream = response.getOutputStream();

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }


        //3.关闭资源
        outputStream.close();
        fileInputStream.close();

    }

    //3.文件删除
    @Operation(summary = "文件删除")
    @GetMapping("/delete")
    public R<Boolean> deleteFile(String fileName)  {
        log.info("文件删除开始");
        log.info("文件名称：" + fileName);
        //删除文件
        boolean delete = fileService.delete(fileName);
        if(!delete){
            return R.error(false, "删除失败");
        }
        return R.success(true, "删除成功");
    }






}
